<template>
  <TablePage>
    <template #top>
      <SearchForm
        ref="searchModalRef"
        title="设备类别"
        :keyword-search-data="[{ label: '设备类别', key: 'searchText' }]"
        add-btn-text="新增设备类别"
        :add-btn-oper-type="OperPermissionType.MANAGE"
        @add="addFn"
        @search="onSearch"
      >
        <template #extraButtons>
          <PermissionBtn v-show="isEnterprise" :oper-type="OperPermissionType.MANAGE" class="mr-4" @click="useTempFn">
            使用标准模板
          </PermissionBtn>
        </template>
      </SearchForm>
    </template>
    <SlTable
      :columns="columns"
      :row-key="isEnterprise ? 'equipmentCategoryId' : 'defaultEquipmentCategoryId'"
      :data-source="tableData"
      :loading="tableLoading"
      :scroll="{ x: true }"
      :search-model="searchModel"
      :pagination="(false as any)"
      :ignore-keys="['parentCategoryId']"
    >
      <template #bodyCell="{ column, record }">
        <a-space v-if="column.key === 'oper'">
          <PermissionBtn
            :oper-type="OperPermissionType.MANAGE"
            :btn-props="{
              type: 'link',
              disabled: record.level > 1,
            }"
            @click="addNextChild(record)"
          >
            新增下级
          </PermissionBtn>
          <PermissionBtn
            :oper-type="OperPermissionType.MANAGE"
            :btn-props="{
              type: 'link',
            }"
            @click="setShowOptions({ action: CURDAction.UPDATE, record })"
          >
            编辑
          </PermissionBtn>
          <PermissionBtn
            :oper-type="OperPermissionType.MANAGE"
            :btn-props="{ type: 'link', danger: true }"
            @click="setShowOptions({ action: CURDAction.DELETE, record })"
          >
            删除
          </PermissionBtn>
        </a-space>
        <div v-if="column.dataIndex === 'equipmentCategoryName'" class="flex flex-row items-center">
          <EllipsisText :max-len="20" :text="record.equipmentCategoryName" />
          <!-- <StateTag
            :color="record.defaultEquipmentCategoryId ? '#4285F4' : '#38CE7B'"
            :value="record.defaultEquipmentCategoryId ? '标准化' : '自定义'"
            class="h-6 ml-2 px-2"
          ></StateTag> -->
        </div>
        <!-- <div v-if="column.dataIndex === 'isActive'">
          <a-switch
            v-model:checked="record.isActive"
            checked-children="开"
            un-checked-children="关"
            @change="handleChangeActiveFn(record)"
          />
        </div> -->
        <EllipsisText
          v-if="column.dataIndex === 'categoryDescription'"
          :max-len="30"
          :text="record.categoryDescription"
        />
      </template>
    </SlTable>
    <CURDDialog
      ref="brandIns"
      create-title="新增设备类别"
      update-title="编辑设备类别"
      delete-message="您确定删除该设备类别吗？"
      :show-options="showOptions"
      :columns="columns"
      :model-form-setting="modelFormSetting"
      :model="model"
      :table-data="tableData"
      :curd="curd"
      :id-key="isEnterprise ? 'equipmentCategoryId' : 'defaultEquipmentCategoryId'"
      :reload-table="reloadTable"
      :get-delete-params="getUserDeleteParams"
      @open="openModal"
      @before-update-model="beforeUpdateModel"
      @before-ok="beforeOk"
      @ok="handleSuccess"
    />
    <a-modal
      v-model:visible="categoryVisible"
      title="使用标准模板"
      width="900px"
      height="600px"
      class="dispatchContainer"
      @ok="handleSelectEquipmentCategory"
    >
      <div ref="content" class="mx-auto">
        <CheckTreePanel
          ref="equipmentCategoryIns"
          v-model:value="selectCategoryKeys"
          v-model:tree-data="equipmentCategoryList"
          v-model:disabledValue="disabledValue"
          search-placeholder="搜索设备类别"
        />
      </div>
    </a-modal>
  </TablePage>
</template>
<script lang="ts" setup>
import { h, onMounted, ref, shallowRef, watch, nextTick } from "vue";
import { useCURD } from "/@/hooks/useCURD";
import {
  pageEquipmentCategorySystem,
  saveOrUpdateEquipmentCategory,
  copyDefaultEquipmentCategory,
  saveOrUpdateEquipmentCategorySys,
} from "/@/api/aiot/equipmentCategory";
import {
  ParEquipmentCategoryItem,
  EquipmentCategorySearchModel,
  EquipmentCategoryItem,
} from "/@/api/aiot/equipmentCategory/models";
import SearchForm from "/@/components/SearchForm.vue";
import PermissionBtn from "/@/components/PermissionBtn.vue";
import { OperPermissionType } from "/@/api/aiot/role/models";
import type { DataNode } from "ant-design-vue/es/tree";
import {
  FormItemData,
  ShowCURDModalOptions,
  CURDAction,
  CURDDialogExpose,
  CURDModalEvent,
  FormItemComponentType,
} from "/@/components/CURDDialog/models";
import SlTable from "/@/components/SlTable.vue";
import { message } from "ant-design-vue";
import { loopItem } from "/@/utils/treeData";
import { useEquipmentCategory } from "./useEquipmentCategory";
import EquipmentCategorySelect from "./EquipmentCategorySelect.vue";

const searchModalRef = ref();
const categoryVisible = ref<boolean>(false);
const selectCategoryKeys = ref<string[]>([]);
const props = defineProps<{
  isEnterprise: boolean;
}>();
const { Api } = useEquipmentCategory(props.isEnterprise);
// 删除多个品牌数据
function delEquipmentCategory() {
  showOptions.value = {
    action: CURDAction.DELETE,
    ids: selectedRowKeys.value,
    message: "您确定要删除已选设备类别吗？",
  };
}
let selectedCategoryKeys = ref<string[]>([]);
async function onSearch(model) {
  await reloadTable({ model });
}
const selectedRowKeys = ref<string[]>([]);
const rowSelection = {
  type: "checkbox",
  selectedRowKeys,
  onChange: (keys) => {
    selectedRowKeys.value = keys;
  },
};
onMounted(async () => {
  await reloadTable({
    size: 9999,
    model: {
      searchText: "",
      parentCategoryId: 0,
    },
  });
  arrayFlagLevel(tableData.value, 0);
  console.info("排序", tableData.value);
});

/**
 * 用户
 */
//用户窗口实例
const brandIns = ref<CURDDialogExpose>();
const { curd, tableData, tableLoading, reloadTable, pagination, searchModel } = useCURD<
  ParEquipmentCategoryItem,
  EquipmentCategorySearchModel
>({
  getPageUrl: Api.pageEquipmentCategory,
  createUrl: Api.saveOrUpdateEquipmentCategory,
  updateUrl: Api.saveOrUpdateEquipmentCategory,
  deleteUrl: Api.deleteEquipmentCategoryByIds,
  loadOnMounted: false,
  onLoadSuccess(data) {
    loopItem(data, (el, i, items) => {
      if (!el.children || el.children.length === 0) {
        delete el.children;
      }
    });
  },
});
watch(
  () => tableData.value,
  () => {
    arrayFlagLevel(tableData.value, 0);
  },
  {
    deep: true,
  }
);
// 自定义删除用户方法
const getUserDeleteParams = (id) => {
  return id ? [id] : selectedCategoryKeys.value;
};
const showOptions = ref<ShowCURDModalOptions>();
function setShowOptions(options: ShowCURDModalOptions) {
  showOptions.value = options;
}
const columns = ref([
  {
    title: "设备类别名称",
    dataIndex: "equipmentCategoryName",
    width: 200,
  },
  {
    title: "备注",
    dataIndex: "categoryDescription",
    width: 200,
  },
  // {
  //   title: "是否启用",
  //   dataIndex: "isActive",
  //   width: 150,
  // },
  {
    title: "操作",
    key: "oper",
    width: 50,
  },
]);
const model = ref<ParEquipmentCategoryItem>({
  equipmentCategoryName: "",
  categoryDescription: "",
  // isActive: true,
});
const modelFormSetting: FormItemData[] = [
  {
    key: "equipmentCategoryName",
    label: "设备类别名称",
    max: 32,
    required: true,
    // pattern: PatternKey.name,
  },
  {
    key: "categoryDescription",
    label: "备注",
    max: 250,
    // pattern: PatternKey.name,
  },
  // {
  //   key: "isActive",
  //   label: "是否启用",
  //   type: FormItemComponentType.SWITCH,
  //   // pattern: PatternKey.name,
  // },
  {
    key: "equipmentCategoryId",
    hide: true,
  },
];

function openModal({ action, formItemData }: CURDModalEvent) {}
function beforeOk(e: CURDModalEvent) {
  if (e.model) {
    const model = e.model as ParEquipmentCategoryItem;
    if (
      e.action === CURDAction.CREATE &&
      (currentSelectRow.value.equipmentCategoryId || currentSelectRow.value.defaultEquipmentCategoryId)
    ) {
      model.parentCategoryId =
        currentSelectRow.value.equipmentCategoryId || currentSelectRow.value.defaultEquipmentCategoryId;
    }
  }
}
function beforeUpdateModel(model: ParEquipmentCategoryItem) {}
/**
 * 操作成功回调
 */
function handleSuccess() {
  selectedRowKeys.value = [];
}
const currentSelectRow = ref<ParEquipmentCategoryItem>({});
function addNextChild(row) {
  currentSelectRow.value = row;
  setShowOptions({ action: CURDAction.CREATE });
}
function addFn() {
  currentSelectRow.value = {};
  setShowOptions({ action: CURDAction.CREATE });
}
async function handleChangeActiveFn(row: ParEquipmentCategoryItem) {
  let req: boolean | null = false;
  if (props.isEnterprise) {
    req = await saveOrUpdateEquipmentCategory(row);
  } else {
    req = await saveOrUpdateEquipmentCategorySys(row);
  }
  if (req) {
    message.success("操作成功");
    reloadTable();
  }
}
const equipmentCategoryList = ref<EquipmentCategoryItem[]>([]);
const equipmentCategoryIns = ref();
const disabledValue = ref<string[]>([]);
function toTree(data, id = "id", pid = "pid") {
  var res: any = [];
  var temp = {};
  for (var i = 0; i < data.length; i++) {
    temp[data[i][id]] = data[i];
  }
  for (var k = 0; k < data.length; k++) {
    if (temp[data[k][pid]] && data[k][id] !== data[k][pid]) {
      if (!temp[data[k][pid]]["children"]) {
        temp[data[k][pid]]["children"] = [];
      }
      temp[data[k][pid]]["children"].push(data[k]);
    } else {
      res.push(data[k]);
    }
  }
  return res;
}

async function useTempFn() {
  const _selectedDefaultIds: string[] = [];
  loopItem(tableData.value, (item) => {
    if (item.defaultEquipmentCategoryId) {
      _selectedDefaultIds.push(item.defaultEquipmentCategoryId);
    }
  });
  disabledValue.value = [..._selectedDefaultIds];
  equipmentCategoryList.value = (await pageEquipmentCategorySystem())?.records || [];
  loopItem(equipmentCategoryList.value, (el, i, items) => {
    if (!el.children || el.children.length === 0) {
      delete el.children;
    }
    el.title = el.equipmentCategoryName;
    el.key = el.defaultEquipmentCategoryId;
  });
  selectCategoryKeys.value = _selectedDefaultIds;
  categoryVisible.value = true;
}
async function handleSelectEquipmentCategory(v) {
  let treeData = equipmentCategoryIns.value?.getCheckedTreeData();
  let treeArr: { defaultEquipmentCategoryId: string; parentId: string }[] = [];
  loopItem(treeData, (item) => {
    treeArr.push({
      defaultEquipmentCategoryId: item.defaultEquipmentCategoryId,
      parentId: item.parentCategoryId,
    });
  });
  let obj = toTree(treeArr, "defaultEquipmentCategoryId", "parentId") || [];
  let req = await copyDefaultEquipmentCategory(obj);
  if (req) {
    categoryVisible.value = false;
    reloadTable();
  }
}
function arrayFlagLevel(array, level) {
  if (!array || !array.length) return;
  array.forEach((item) => {
    item.level = level;
    if (item.children && item.children.length) {
      arrayFlagLevel(item.children, level + 1);
    }
  });
}
</script>
